<template>
  <div class="page-content">
    <div class="header">
      <h3>设备管理</h3>
    </div>

    <div class="actions-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchKeyword" placeholder="搜索设备..." clearable @keyup.enter="handleSearchChange" @clear="handleSearchChange">
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-select v-model="selectedNodeId" placeholder="选择节点" clearable style="width: 100%" @change="handleFilterChange">
            <el-option label="全部节点" value="" />
            <el-option
              v-for="node in nodeList"
              :key="node.service_id"
              :label="node.service_name"
              :value="node.service_id"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="selectedStatus" placeholder="设备状态" clearable style="width: 100%" @change="handleFilterChange">
            <el-option label="全部状态" value="" />
            <el-option label="在线" :value="true" />
            <el-option label="离线" :value="false" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="selectedVipLevel" placeholder="套餐等级" clearable style="width: 100%" @change="handleFilterChange">
            <el-option label="全部等级" value="" />
            <el-option
              v-for="pkg in vipPackages"
              :key="pkg.id"
              :label="pkg.vip_name"
              :value="pkg.level"
            />
          </el-select>
        </el-col>
        <el-col :span="9" class="action-buttons">
          <el-button type="primary" @click="goToScanPage" v-ripple>扫描设备</el-button>
          <el-button @click="refresh" v-ripple>刷新列表</el-button>
          <el-button type="warning" @click="batchConfig" :disabled="selectedDevices.length === 0" v-ripple>
            批量配置
          </el-button>
          <el-button type="danger" @click="batchDelete" :disabled="selectedDevices.length === 0" v-ripple>
            批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="device-stats">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover">
            <div class="stat-item">
              <div class="stat-icon online">
                <el-icon><monitor /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">在线设备</div>
                <div class="stat-value">{{ onlineCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <div class="stat-item">
              <div class="stat-icon offline">
                <el-icon><warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">离线设备</div>
                <div class="stat-value">{{ offlineCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <div class="stat-item">
              <div class="stat-icon total">
                <el-icon><tickets /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">总设备数</div>
                <div class="stat-value">{{ total }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="device-table">
      <el-table
        v-loading="loading"
        :data="filteredDevices"
        stripe
        border
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column 
          type="selection" 
          width="45" 
          :selectable="(row) => !row.rent_status && row.online_status"
        />
        <el-table-column prop="id" label="ID" sortable="custom" width="80" />
        <el-table-column prop="serviceIP" label="服务器名称" min-width="100">
          <template #default="scope">{{ scope.row.serviceIP || '-' }}</template>
        </el-table-column>
        <el-table-column prop="model" label="设备型号" min-width="100" />
        <el-table-column prop="local_ip" label="设备IP" min-width="100">
          <template #default="scope">{{ scope.row.local_ip || '-' }}</template>
        </el-table-column>
        <el-table-column prop="android_version" label="安卓版本" min-width="80" sortable="custom">
          <template #default="scope">{{ scope.row.android_version || '-' }}</template>
        </el-table-column>
    
        <el-table-column prop="adb_type" label="免ADB设备" min-width="80" sortable="custom">
          <template #default="scope">
            <el-tag :type="scope.row.adb_type ? 'success' : 'info'">{{ scope.row.adb_type ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="online_status" label="在线状态" min-width="80" sortable="custom">
          <template #default="scope">
            <el-tag :type="scope.row.online_status ? 'success' : 'danger'">{{ scope.row.online_status ? '在线' : '离线' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="可租借状态" min-width="80" sortable="custom">
          <template #default="scope">
            <el-tag :type="scope.row.Status ? 'success' : 'danger'">{{ scope.row.Status ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="vip_level" label="套餐等级" min-width="80" sortable="custom">
          <template #default="scope">
            {{ getVipName(scope.row.vip_level) }}
          </template>
        </el-table-column>
        <el-table-column prop="rent_status" label="租借状态" min-width="80" sortable="custom">
          <template #default="scope">
            <el-tag :type="scope.row.rent_status ? 'success' : 'info'">{{ scope.row.rent_status ? '已租借' : '未租借' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="over_time" label="到期时间" min-width="120" sortable="custom" />

        <el-table-column prop="created_at" label="创建时间" min-width="120" sortable="custom" />
        <el-table-column prop="updated_at" label="更新时间" min-width="120" sortable="custom" />
        <el-table-column fixed="right" label="操作" width="280">
          <template #default="scope">
            <div style="display: flex; gap: 5px;">
              <el-button size="small" type="primary" @click="openDetail(scope.row)" plain>详情</el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="openConfig(scope.row)" 
                plain
                :disabled="scope.row.rent_status || !scope.row.online_status"
                :title="scope.row.rent_status ? '已租借设备不可配置' : (!scope.row.online_status ? '离线设备不可配置' : '')"
              >配置</el-button>
              <el-button 
                size="small" 
                type="warning" 
                @click="openCommandDialog(scope.row)" 
                plain
                :disabled="!scope.row.adb_type || !scope.row.online_status"
                :title="!scope.row.adb_type ? '非ADB免设备未开发此功能' : (!scope.row.online_status ? '设备离线不可执行命令' : '')"
              >命令</el-button>
              <el-button size="small" type="danger" @click="removeDevice(scope.row)" plain>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>

    <!-- 设备详情对话框 -->
    <el-dialog title="设备详情" v-model="detailVisible" width="60%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备类型">
          <el-tag :type="!currentDevice.adb_type ? 'warning' : 'success'">
            {{ !currentDevice.adb_type ? 'ADB设备' : '免ADB设备' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="设备IP">{{ currentDevice.identification_number }}</el-descriptions-item>
        <el-descriptions-item label="安卓版本">{{ currentDevice.android_version }}</el-descriptions-item>
        <el-descriptions-item label="服务器名称">{{ currentDevice.serviceIP }}</el-descriptions-item>
        <el-descriptions-item label="在线状态">
          <el-tag :type="currentDevice.online_status ? 'success' : 'danger'">
            {{ currentDevice.online_status ? '在线' : '离线' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="可租借状态">
          <el-tag :type="currentDevice.Status ? 'success' : 'danger'">
            {{ currentDevice.Status ? '可租借' : '不可租借' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="套餐等级">{{ getVipName(currentDevice.vip_level) }}</el-descriptions-item>
        <el-descriptions-item label="租借状态">
          <el-tag :type="currentDevice.rent_status ? 'success' : 'info'">
            {{ currentDevice.rent_status ? '已租借' : '未租借' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="到期时间">{{ currentDevice.over_time }}</el-descriptions-item>

        <el-descriptions-item label="创建时间">{{ currentDevice.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentDevice.updated_at }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="device-detail-tabs">
        <el-tabs>
          <el-tab-pane label="手机参数">
            <el-descriptions :column="2" border>
              <template v-if="currentDevice.phoneParams">
                <el-descriptions-item v-for="(value, key) in currentDevice.phoneParams" :key="key" :label="key">
                  {{ value || '-' }}
                </el-descriptions-item>
              </template>
              <el-descriptions-item v-else label="手机参数" :span="2">暂无数据</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 设备配置对话框 -->
    <el-dialog 
      :title="selectedDevices.length > 1 ? '批量配置设备' : '设备配置'" 
      v-model="configVisible" 
      width="50%"
    >
      <div v-if="selectedDevices.length > 1" class="batch-config-tip">
        <el-alert
          title="批量配置将修改所选设备的套餐等级和可租借状态"
          type="warning"
          :closable="false"
          show-icon
        />
        <el-alert
          style="margin-top: 10px;"
          title="注意：只有在线的设备才能被配置，离线设备无法修改"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
      <el-form :model="configForm" label-width="120px">
        <el-form-item label="套餐等级">
          <el-select v-model="configForm.vip_level" style="width: 100%" clearable placeholder="请选择套餐等级">
            <el-option
              v-for="pkg in vipPackages"
              :key="pkg.id"
              :label="pkg.vip_name"
              :value="pkg.level"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否可租借">
          <el-switch
            v-model="configForm.status"
            :active-value="true"
            :inactive-value="false"
            active-text="可租借"
            inactive-text="不可租借"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="configVisible = false">取消</el-button>
          <el-button type="primary" @click="saveConfig" :loading="isSaving">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备命令对话框 -->
    <el-dialog title="执行设备命令" v-model="commandDialogVisible" width="50%">
      <el-alert
        v-if="currentDevice.adb_type"
        title="请谨慎执行命令，错误的命令可能导致设备异常"
        type="warning"
        :closable="false"
        show-icon
      />
      <el-form :model="commandForm" label-width="100px" style="margin-top: 20px;">
        <el-form-item label="设备信息">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="设备型号">{{ currentDevice.model || '-' }}</el-descriptions-item>
            <el-descriptions-item label="设备IP">{{ currentDevice.local_ip || '-' }}</el-descriptions-item>
            <el-descriptions-item label="外网IP">{{ currentDevice.actual_ip || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-form-item>
        <el-form-item label="执行命令">
          <el-input 
            v-model="commandForm.command" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入要执行的命令"
          />
        </el-form-item>
      </el-form>
      
      <div v-if="commandResult" class="command-result">
        <h4>执行结果：</h4>
        <pre>{{ JSON.stringify(commandResult, null, 2) }}</pre>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commandDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="executeCommand" :loading="isExecutingCommand">执行</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Monitor, Warning, Bell, Tickets } from '@element-plus/icons-vue'
import { 
  getDeviceList, 
  getNodeList, 
  modifyPhone, 
  getVipPackages, 
  deleteDevice,
  execDeviceCommand,
  type VipPackage,
  type DeviceQueryParams 
} from '@/Newapi/device'

// 路由器
const router = useRouter()

// 加载状态
const loading = ref(false)

// 搜索关键词
const searchKeyword = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 排序
const sortColumn = ref('')
const sortOrder = ref<'asc' | 'desc' | ''>('')

// 过滤条件
const selectedNodeId = ref('')
const selectedStatus = ref<boolean | ''>('')
const selectedVipLevel = ref<number | ''>('')

// 定义设备类型接口
interface Device {
  id: number
  name: string
  ip: string
  mac: string
  type: 'adb' | 'network' | 'other'
  status: 'online' | 'offline' | 'warning'
  location: string
  lastOnline: string
  description: string
  firmware: string
  hardware: string
  model: string
  manufacturer: string
  serialNumber: string
  purchaseDate?: string
  alerts?: Array<{
    level: 'high' | 'medium' | 'low'
    message: string
    time: string
  }>
  phoneParams?: Record<string, any>
}

// 定义API返回的设备数据接口
interface DeviceApiData {
  id: number
  created_at: string
  updated_at: string
  IP: string | null
  Port: number | null
  phone_parameter: string
  Status: boolean
  online_status: boolean
  identification_number: string
  android_version: string
  vip_level: number
  rent_status: boolean
  serviceIP: string
  adb_type: boolean
  over_time: string
  actual_ip?: string
}

// 定义手机参数接口
interface PhoneParams {
  model?: string
  serial?: string
  local_ip?: string
  android_version?: string
  hardware?: string
  manufacturer?: string
  brand?: string
  [key: string]: any
}

// 设备列表
const deviceList = ref<Device[]>([])
const total = ref(0)

// 选中的设备
const selectedDevices = ref<Device[]>([])

// 设备详情对话框
const detailVisible = ref(false)
const currentDevice = reactive({
  id: '',
  name: '',
  ip: '',
  mac: '',
  type: '',
  status: '',
  location: '',
  lastOnline: '',
  description: '',
  firmware: '',
  hardware: '',
  model: '',
  manufacturer: '',
  serialNumber: '',
  purchaseDate: '',
  alerts: [] as any[],
  phoneParams: {} as Record<string, any>
})

// 设备配置对话框
const configVisible = ref(false)
const configForm = reactive({
  id: '',
  vip_level: undefined as number | undefined,
  status: false as boolean
})

// 保存加载状态
const isSaving = ref(false)

// 手机参数字段映射
const phoneParamsMap = {
  'CPU架构': 'CPUæ¶æ',
  'CPU核心数': 'CPUæ ¸å¿æ°',
  '处理器型号': 'å¤çå¨åå·',
  '手机名称': 'ææºçåç§°',
  '手机运营商': 'ææºçè¿è¥å',
  '运行内存': 'è¿è¡åå­',
  '品牌': 'brand',
  '设备代号': 'device',
  '磁盘使用': 'disk_usage',
  '硬件': 'hardware',
  '制造商': 'manufacturer',
  '产品名': 'product',
  'SDK版本': 'sdk_version',
  '序列号': 'serial'
}

// 计算属性：过滤后的设备列表
const filteredDevices = computed(() => {
  if (!searchKeyword.value) {
    return deviceList.value
  }
  const keyword = searchKeyword.value.toLowerCase()
  return deviceList.value.filter(
    (device) =>
      device.name.toLowerCase().includes(keyword) ||
      device.ip.toLowerCase().includes(keyword) ||
      device.mac.toLowerCase().includes(keyword) ||
      (device.location && device.location.toLowerCase().includes(keyword))
  )
})

// 计算属性：在线设备数量
const onlineCount = computed(() => {
  return deviceList.value.filter((device) => device.status === 'online').length
})

// 计算属性：离线设备数量
const offlineCount = computed(() => {
  return deviceList.value.filter((device) => device.status === 'offline').length
})

// 兼容中文key的Base64解码
function decodeBase64Utf8(str: string) {
  try {
    return decodeURIComponent(escape(window.atob(str)));
  } catch (e) {
    return atob(str);
  }
}

// 节点相关
const nodeList = ref<any[]>([])

// 获取节点列表
const fetchNodeList = async () => {
  try {
    const result = await getNodeList()
    if (result.code === 200) {
      nodeList.value = Object.entries(result.data).map(([key, node]: [string, any]) => ({
        service_id: node.service_id,
        service_name: node.service_name
      }))
    } else {
      ElMessage.error(result.msg || '获取节点列表失败')
    }
  } catch (error) {
    console.error('获取节点列表失败:', error)
    ElMessage.error('获取节点列表失败')
  }
}

// 处理过滤条件变化
const handleFilterChange = () => {
  currentPage.value = 1 // 重置页码
  loadDeviceList()
}

// 处理搜索变化
const handleSearchChange = () => {
  currentPage.value = 1 // 重置页码
  loadDeviceList()
}

// 处理排序变化
const handleSortChange = (column: { prop: string, order: string }) => {
  // 从el-table的排序规则转换为API接口需要的格式
  sortColumn.value = column.prop || ''
  
  if (column.order === 'ascending') {
    sortOrder.value = 'asc'
  } else if (column.order === 'descending') {
    sortOrder.value = 'desc'
  } else {
    sortOrder.value = ''
  }
  
  currentPage.value = 1 // 重置页码
  loadDeviceList()
}

// 加载设备列表
const loadDeviceList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const queryParams: DeviceQueryParams = {
      page: currentPage.value,
      page_size: pageSize.value
    }
    
    // 添加服务名称过滤
    if (selectedNodeId.value) {
      queryParams.service_name = selectedNodeId.value
    }
    
    // 添加排序参数
    if (sortColumn.value && sortOrder.value) {
      queryParams.sort = sortColumn.value
      queryParams.order = sortOrder.value
    }
    
    // 创建where对象用于条件过滤
    const whereConditions: DeviceQueryParams['where'] = {}
    let hasConditions = false
    
    // 添加搜索关键词过滤
    if (searchKeyword.value) {
      whereConditions.identification_number = searchKeyword.value
      hasConditions = true
    }
    
    // 添加状态过滤
    if (selectedStatus.value !== '') {
      whereConditions.status = selectedStatus.value
      hasConditions = true
    }
    
    // 添加VIP等级过滤
    if (selectedVipLevel.value !== '') {
      whereConditions.vip_level = selectedVipLevel.value
      hasConditions = true
    }
    
    // 如果有过滤条件，添加到查询参数中
    if (hasConditions) {
      queryParams.where = whereConditions
    }
    
    const result = await getDeviceList(queryParams)
    
    if (result.code === 200) {
      // 处理设备数据
      deviceList.value = result.data.list.map((device: DeviceApiData) => {
        let phoneParams: PhoneParams = {}
        try {
          phoneParams = JSON.parse(decodeBase64Utf8(device.phone_parameter))
        } catch (e) {
          console.error('解析phone_parameter失败:', e)
        }
        return {
          id: device.id,
          model: phoneParams.model || device.identification_number || '-',
          local_ip: device.identification_number || '-',
          android_version: device.android_version || '-',
          serviceIP: device.serviceIP || '-',
          adb_type: device.adb_type,
          created_at: device.created_at,
          updated_at: device.updated_at,
          Status: device.Status,
          over_time: device.over_time,
          online_status: device.online_status,
          vip_level: device.vip_level,
          rent_status: device.rent_status,
          actual_ip: device.actual_ip || '-',
          // 兼容旧字段，详情页等用
          name: phoneParams.model || device.identification_number,
          ip: phoneParams.local_ip || device.identification_number,
          mac: phoneParams.serial || '-',
          type: device.adb_type ? 'adb' : 'network',
          status: device.online_status ? 'online' : 'offline',
          location: phoneParams.local_ip || '-',
          lastOnline: device.updated_at,
          description: '',
          firmware: phoneParams.android_version || device.android_version,
          hardware: phoneParams.hardware || '-',
          manufacturer: phoneParams.manufacturer || phoneParams.brand || '-',
          serialNumber: phoneParams.serial || '-',
          phoneParams // 仅详情页用
        }
      })
      total.value = result.data.total
    } else {
      ElMessage.error(result.msg || '获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表出错:', error)
    ElMessage.error('获取设备列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 监听分页变化
watch([currentPage, pageSize], () => {
  loadDeviceList()
})

// 在 script setup 中添加套餐列表相关的变量和方法
const vipPackages = ref<VipPackage[]>([])

// 获取套餐列表
const fetchVipPackages = async () => {
  try {
    const result = await getVipPackages()
    if (result.code === 200) {
      vipPackages.value = result.data
    } else {
      ElMessage.error(result.msg || '获取套餐列表失败')
    }
  } catch (error) {
    console.error('获取套餐列表失败:', error)
    ElMessage.error('获取套餐列表失败')
  }
}

// 获取套餐名称的方法
const getVipName = (level: number) => {
  const package_ = vipPackages.value.find(p => p.level === level)
  return package_?.vip_name || '-'
}

// 页面初始化时加载节点列表和设备列表
onMounted(async () => {
  await fetchVipPackages() // 获取套餐列表
  await fetchNodeList() // 获取节点列表
  await loadDeviceList() // 获取设备列表
})

// 刷新设备列表
const refresh = () => {
  loadDeviceList()
  ElMessage.success('设备列表已刷新')
}

// 跳转到扫描页面
const goToScanPage = () => {
  router.push('/cloudDevice/deviceScan')
}

// 打开设备详情
const openDetail = (device: any) => {
  Object.assign(currentDevice, {
    ...device,
    // 确保API返回的字段都被正确传递
    adb_type: device.adb_type,
    identification_number: device.local_ip,
    android_version: device.android_version,
    serviceIP: device.serviceIP,
    Status: device.Status,
    online_status: device.online_status,
    vip_level: device.vip_level,
    rent_status: device.rent_status,
    created_at: device.created_at,
    updated_at: device.updated_at,
    over_time:device.over_time,
    phoneParams: device.phoneParams || {}
  })
  
  // 添加随机报警记录
  if (!currentDevice.alerts || currentDevice.alerts.length === 0) {
    currentDevice.alerts = generateMockAlerts()
  }
  detailVisible.value = true
}

// 打开设备配置
const openConfig = (device: any) => {
  selectedDevices.value = [device] // 单个配置时，设置选中设备为当前设备
  Object.assign(configForm, {
    id: device.id,
    vip_level: device.vip_level,
    status: device.Status
  })
  configVisible.value = true
}

// 批量配置
const batchConfig = () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请先选择要配置的设备')
    return
  }
  
  // 重置配置表单，设置默认值
  Object.assign(configForm, {
    vip_level: undefined,
    status: false // 设置默认值为离线状态
  })
  configVisible.value = true
}

// 修改保存设备配置的方法
const saveConfig = async () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请选择要配置的设备')
    return
  }

  // 构建要发送的数据
  const data: {
    modify_id: number[]
    vip_level?: number
    status: boolean // 状态值始终发送
  } = {
    modify_id: selectedDevices.value.map(device => device.id),
    status: configForm.status // 直接使用开关的值
  }

  // 只有当套餐等级有值时才添加
  if (configForm.vip_level !== undefined) {
    data.vip_level = configForm.vip_level
  }

  try {
    isSaving.value = true
    const result = await modifyPhone(data)

    if (result.code === 200) {
      ElMessage.success(selectedDevices.value.length > 1 ? '批量配置成功' : '设备配置已保存')
      configVisible.value = false
      // 刷新设备列表
      loadDeviceList()
      // 清空选择image.png
      if (selectedDevices.value.length > 1) {
        selectedDevices.value = []
      }
    } else {
      ElMessage.error(result.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存设备配置出错:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    isSaving.value = false
  }
}

// 删除设备
const removeDevice = (device: any) => {
  ElMessageBox.confirm(`确定要删除设备 "${device.name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        const result = await deleteDevice(device.id)
        
        if (result.code === 200) {
          deviceList.value = deviceList.value.filter((item) => item.id !== device.id)
          ElMessage.success('设备已删除')
        } else {
          ElMessage.error(result.msg || '删除设备失败')
        }
      } catch (error) {
        console.error('删除设备出错:', error)
        ElMessage.error('删除设备失败，请重试')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {})
}

// 批量删除设备
const batchDelete = () => {
  if (selectedDevices.value.length === 0) return

  const deviceNames = selectedDevices.value.map((device) => device.name).join('、')
  ElMessageBox.confirm(`确定要删除以下设备吗？\n${deviceNames}`, '批量删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        const ids = selectedDevices.value.map((device) => device.id)
        
        // 依次删除每个设备
        const deletePromises = ids.map(id => deleteDevice(id))
        const results = await Promise.allSettled(deletePromises)
        
        // 统计成功和失败的数量
        const successCount = results.filter(r => r.status === 'fulfilled' && (r.value as any).code === 200).length
        const failCount = ids.length - successCount
        
        // 刷新列表显示
        loadDeviceList()
        
        if (failCount === 0) {
          ElMessage.success(`已成功删除 ${successCount} 台设备`)
        } else {
          ElMessage.warning(`成功删除 ${successCount} 台设备，${failCount} 台设备删除失败`)
        }
        
        // 清空选择
        selectedDevices.value = []
      } catch (error) {
        console.error('批量删除设备出错:', error)
        ElMessage.error('批量删除设备失败，请重试')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {})
}

// 表格选择变化
const handleSelectionChange = (selection: Device[]) => {
  // 确保已租借设备和离线设备不会被选中（双重保险）
  selectedDevices.value = selection.filter(device => !device.rent_status && device.online_status)
}

// 获取设备类型名称
const getDeviceTypeName = (type: 'adb' | 'network' | 'other') => {
  const typeMap = {
    adb: 'ADB设备',
    network: '网络设备',
    other: '其他'
  }
  return typeMap[type] || '未知'
}

// 获取状态类型
const getStatusType = (status: 'online' | 'offline' | 'warning') => {
  const statusMap = {
    online: 'success',
    offline: 'danger',
    warning: 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态名称
const getStatusName = (status: 'online' | 'offline' | 'warning') => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    warning: '告警'
  }
  return statusMap[status] || '未知'
}

// 生成模拟告警记录
const generateMockAlerts = () => {
  const alerts = []
  const levels = ['high', 'medium', 'low']
  const messages = [
    '设备连接超时',
    '设备温度过高',
    'CPU使用率超过90%',
    '内存使用率超过95%',
    '网络带宽异常',
    '磁盘空间不足',
    'PING响应时间过长',
    '接口错误率超过阈值',
    '设备重启',
    '固件版本过旧'
  ]

  // 生成1-5条随机告警记录
  const alertCount = Math.floor(Math.random() * 5) + 1
  const now = new Date()

  for (let i = 0; i < alertCount; i++) {
    const days = Math.floor(Math.random() * 30)
    const hours = Math.floor(Math.random() * 24)
    const minutes = Math.floor(Math.random() * 60)
    const alertTime = new Date(now.getTime() - days * 24 * 60 * 60 * 1000 - hours * 60 * 60 * 1000 - minutes * 60 * 1000)

    alerts.push({
      level: levels[Math.floor(Math.random() * levels.length)],
      message: messages[Math.floor(Math.random() * messages.length)],
      time: alertTime.toLocaleString()
    })
  }

  // 按时间排序，最新的在最前
  return alerts.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
}

// 获取手机参数值的方法
const getPhoneParamValue = (label: string) => {
  const key = phoneParamsMap[label]
  return currentDevice.phoneParams?.[key] || '-'
}

// 设备命令对话框
const commandDialogVisible = ref(false)
const commandForm = reactive({
  command: ''
})
const commandResult = ref<any>(null)
const isExecutingCommand = ref(false)

// 打开命令对话框
const openCommandDialog = (device: any) => {
  if (!device.adb_type) {
    ElMessage.warning('非ADB免设备未开发此功能')
    return
  }
  
  if (!device.online_status) {
    ElMessage.warning('设备离线不可执行命令')
    return
  }
  
  Object.assign(currentDevice, {
    ...device,
    actual_ip: device.actual_ip || '-'
  })
  
  // 重置命令表单和结果
  commandForm.command = ''
  commandResult.value = null
  commandDialogVisible.value = true
}

// 执行设备命令
const executeCommand = async () => {
  if (!commandForm.command.trim()) {
    ElMessage.warning('请输入要执行的命令')
    return
  }
  
  try {
    isExecutingCommand.value = true
    const result = await execDeviceCommand(
      currentDevice.local_ip,
      currentDevice.actual_ip,
      commandForm.command.trim()
    )
    
    commandResult.value = result
    
    if (result.code === 0) {
      ElMessage.success('命令发送成功')
    } else {
      ElMessage.error(result.msg || '命令执行失败')
    }
  } catch (error) {
    console.error('执行设备命令出错:', error)
    commandResult.value = {
      code: -1,
      msg: '请求出错: ' + (error.message || '未知错误')
    }
    ElMessage.error('执行命令失败，请检查网络连接')
  } finally {
    isExecutingCommand.value = false
  }
}

</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .actions-bar {
    margin: 20px 0;
    
    .action-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }

  .device-stats {
    margin-bottom: 20px;
    
    .stat-item {
      display: flex;
      align-items: center;
      
      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        
        .el-icon {
          font-size: 24px;
          color: white;
        }
        
        &.online {
          background-color: #67c23a;
        }
        
        &.offline {
          background-color: #f56c6c;
        }
        
        &.warning {
          background-color: #e6a23c;
        }
        
        &.total {
          background-color: #409eff;
        }
      }
      
      .stat-info {
        .stat-title {
          font-size: 14px;
          color: #909399;
        }
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
        }
      }
    }
  }

  .device-table {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .device-detail-tabs {
    margin-top: 20px;
    
    .chart-container {
      height: 300px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f7fa;
      border-radius: 4px;
      
      .chart-placeholder {
        color: #909399;
      }
    }
  }

  .batch-config-tip {
    margin-bottom: 20px;
  }

  .command-result {
    margin-top: 20px;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    max-height: 200px;
    overflow-y: auto;
    
    pre {
      margin: 0;
      white-space: pre-wrap;
      word-break: break-all;
    }
  }
}
</style> 